package com.zkthink.ceres.promotion.service.impl;

import com.zkthink.base.R;
import com.zkthink.ceres.promotion.dao.CouponMapper;
import com.zkthink.ceres.promotion.dao.MemberCouponMapper;
import com.zkthink.ceres.promotion.entity.Coupon;
import com.zkthink.ceres.promotion.entity.MemberCoupon;
import com.zkthink.ceres.promotion.service.MemberCouponService;
import com.zkthink.base.service.SuperServiceImpl;

import com.zkthink.ceres.promotion.vo.web.CouponPageVO;
import com.zkthink.ceres.promotion.vo.web.CouponVO;
import com.zkthink.database.mybatis.conditions.Wraps;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 业务实现类
 * 用户领券表
 * </p>
 *
 * @author JustArgo
 * @date 2020-06-26
 */
@Slf4j
@AllArgsConstructor
@Service
public class MemberCouponServiceImpl extends SuperServiceImpl<MemberCouponMapper, MemberCoupon> implements MemberCouponService {

    private CouponMapper couponMapper;

    @Override
    public R<Boolean> receiveCoupon(Long mid, Long couponId) {
        if(mid==null || mid==0){
            return R.fail(-1,"用户信息异常");
        }
        if(couponId==null || couponId==0){
            return R.fail(-1,"优惠券id不正确");
        }
        Integer count = baseMapper.selectCount(Wraps.<MemberCoupon>lbQ().eq(MemberCoupon::getMid,mid).eq(MemberCoupon::getCouponId,couponId).eq(MemberCoupon::getIsDeleted,0));
        if(count==0){
            Coupon coupon = couponMapper.selectById(couponId);
            if(coupon==null){
                return R.fail(-1,"优惠券不存在,无法领取");
            }
            if(coupon.getPublishStartTime().isAfter(LocalDateTime.now())
                || coupon.getPublishEndTime().isBefore(LocalDateTime.now())) {
                return R.fail(-1,"优惠券未到领取时间，或已失效，无法领取");
            }
            MemberCoupon memberCoupon = new MemberCoupon();
            memberCoupon.setMid(mid);
            memberCoupon.setCouponId(couponId);
            memberCoupon.setReceiveTime(LocalDateTime.now());
            baseMapper.insert(memberCoupon);
        }else{
            return R.fail(-1,"您已领取过该优惠券不能再次领取");
        }
        return R.success();
    }

	@Override
	public R<CouponPageVO> findCouponList(Long mid, Integer pageIndex, Integer pageSize) {
        if(mid==null || mid==0){
            return R.success(new CouponPageVO(0,new ArrayList<>()));
        }
        Integer total = baseMapper.findCouponListCount(mid);
        List<CouponVO> couponVOList = baseMapper.findCouponList(mid,(pageIndex-1),pageSize);

		return R.success(new CouponPageVO(total,couponVOList));
	}

	@Override
	public void useCoupon(Long mid, Long couponId) {
        if (mid == null || couponId == null || mid == 0 || couponId == 0) {
		    return;
        }
        baseMapper.useCoupon(mid,couponId);
	}
}
